package org.tinygroup.template.function;

import java.net.URLDecoder;

import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.template.Template;
import org.tinygroup.template.TemplateContext;
import org.tinygroup.template.TemplateException;

public class UrlDecodeFunction extends AbstractTemplateFunction {

	public UrlDecodeFunction() {
		super("urldecode");
	}

	public Object execute(Template template, TemplateContext context,
			Object... parameters) throws TemplateException {
		if (parameters == null || parameters.length < 1) {
            throw new TemplateException("urldecode函数必须输入转换的参数");
        }
		
		try {
			String s = (String) parameters[0];
			//增加空值处理
			if(StringUtil.isEmpty(s)){
			   return s;
			}
			String encode = "utf-8";
			if(parameters.length>=2 && parameters[1]!=null){
				encode = (String) parameters[1];
			}
			return URLDecoder.decode(s, encode);
		} catch (Exception e) {
			throw new TemplateException(e);
		}
	}

}
